Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

write a program to create queue class and implement all its methods (use lists) in python

write a program to create queue class and implement all its methods (use lists) in python
1 min read

 

What is the Queue?

A queue is a linear type of data structure used to store the data in a sequentially. The concept of queue is based on the FIFO, which means "First in First Out". It is also known as "first come first severed". The queue has the two ends front and rear. The next element is inserted from the rear end and removed from the front end.

For example - There are 20 computers in the computer science lab and connected to a single printer. The students want to print their paper; the printer will print the first task and second, so on. If we are the last in line, we need to wait until all other tasks are completed that ahead of ours.

The built-in Python List

The list can be used as the queue, but it is not suitable for a performance perspective. Python provides built-in methods insert() and pop() function to add and remove elements. Lists are quite slow because if we insert a new element to the list, all elements require shifting by one. It takes O(n) time. So lists are recommended in-place of queue. Let's understand the following example of how a list can be used as a queue.

Example -

  1. que = []  
  2.   
  3. que.append('Apple')  
  4. que.append('Mango')  
  5. que.append('Papaya')  
  6.   
  7. print(que)  
  8.   
  9. # List is slow!  
  10. print(que.pop(0))  

Output:

['Apple', 'Mango', 'Papaya']
Apple

Explanation -

We have defined the empty list in the above code and inserted a few elements using append() method. It will add an element to the end of the list.

You may like these posts

Post a Comment

© 2025Python . The Best Codder All rights reserved. Distributed by